﻿using System.Collections.Generic;
using DataFiller.DataStorage.Extension;
using DataFiller.DataStorage.Extension.ExcelOperator;
using DataFiller.DataStorage.Extension.Regions;
using NPOI.SS.UserModel;

namespace DataFiller.ExportWithNpoi
{
    public class NRow : IExcelRow
    {
        public int RowNum
        {
            get
            {
                return _row.RowNum;
            }
        }
        private IRow _row;

        public NRow(IRow row)
        {
            this._row = row;
        }

        #region IExcelRow

        public void RowHandler(ExportContext context)
        {
            //when a row without any data, won't loaded by npoi, so we add the region manully
            while (context.ContinuousRowCount < _row.RowNum)
            {
                context.DataMap.AddRegion
                (
                    context.ContinuousRowCount,
                    new ExcelRowRegion<int>
                    {
                        TemplateRowNumber = context.ContinuousRowCount
                    }
                );

                context.ContinuousRowCount++;
            }

            context.DataMap.AddRegion
            (
                _row.RowNum,
                new ExcelRowRegion<int>
                {
                    TemplateRowNumber = _row.RowNum
                }
            );

            context.ContinuousRowCount = _row.RowNum + 1;
        }
        public IEnumerator<IExcelCell> GetEnumerator()
        {
            foreach (ICell cell in _row)
                yield return new NCell(cell);
        }
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }
        public IExcelCell GetOrCreateColByIndex(int index)
        {
            ICell tempCell = _row.GetCell(index);
            return tempCell == null ?
                new NCell(_row.CreateCell(index)) :
                new NCell(tempCell);
        }
        #endregion
    }
}
